import React, { useEffect, useRef, useState } from "react"

import { useLocale } from "@/locales"

import Active from "./Active"
import ColumnHeader from "./ColumnHeader"
import DraggableColumn from "./DraggableColumn"
import { STable } from "./index.styled"
import Statistics from "./Statistics"

// interface IDraggableColumnProps {
// 	key: string
// 	title: string | Function | React.ReactNode
// 	titleText: string
// 	fixed: boolean
// 	index?: number
// 	sortable?: boolean
// }

interface TableProps {
	data: any[]
	columns: any[]
	onSort?: (columnName: string, sortOrder: "asc" | "desc") => void
	onExport?: () => void
	showRowSet?: boolean | undefined
	onColumnDrag?: (sourceIndex: number, destinationIndex: number) => void
	columnStyles?: React.CSSProperties[]
	rowSelection?: object
	sortData?: (columnName: string, sortOrder: "asc" | "desc") => any[]
	onPageChange?: (current: number, pageSize: number) => void
	onChange?: (pagination: any, filters: any, sorter: any, extra: any) => void
	otherProps?: any
	scroll: any
	statisticDom?: (() => React.ReactNode | string | undefined) | React.ReactNode | string | undefined
	tableId: string
	loading: boolean
	statisticText: string | undefined
	rowKey?: any
	pagination?:
		| {
				current: number
				pageSize: number
				total: number
				showSizeChanger?: boolean
				showTotal?: (total: number) => string
				showQuickJumper?: boolean
		  }
		| false
	summary?: () => JSX.Element
	sticky?: { offsetHeader?: number }
	changeColumns?: (columns: any[]) => void
	footer?: () => JSX.Element
}

const DropTable: React.FC<TableProps> = ({
	data,
	columns,
	onSort,
	onPageChange,
	onExport,
	showRowSet,
	onColumnDrag,
	onChange,
	scroll,
	statisticDom,
	tableId,
	loading,
	statisticText,
	pagination,
	rowSelection,
	summary,
	sticky,
	rowKey,
	changeColumns: propsChangeColumns,
	footer,
	...otherProps
}) => {
	const { formatMessage } = useLocale()
	const tableRef = useRef(null)
	// const [tableId] = useState(Math.random().toFixed(5).substring(2))
	// // 拖拽
	const [columnsOrder, setColumnsOrder] = useState<any[]>([...columns])
	useEffect(() => {
		setColumnsOrder([...columns])
	}, [columns])
	// 防止更新不及时
	const columnsRef = useRef(columnsOrder)
	// 排序
	const handleSort = (columnName: string) => {
		if (onSort) {
			onSort(columnName, "asc") // 默认以升序排序
		}
	}
	// 可以配置
	const pageSizeOptions = [10, 20, 50, 100, 200]
	// 拖拽
	const handleDrag = (sourceIndex: number, destinationIndex: number) => {
		// 找到正确的索引
		const _sourceIndex = columnsRef.current.findIndex(i => i.index === sourceIndex)
		const _destinationIndex = columnsRef.current.findIndex(i => i.index === destinationIndex)
		// 如果有固定列则不执行
		// 先都不让拖拽
		if (!columnsRef.current[_sourceIndex].fixed || !columnsRef.current[_destinationIndex].fixed) {
			console.log("固定列不可替换")
			return false
		}
		// 回调传值
		if (onColumnDrag) {
			onColumnDrag(_sourceIndex, _destinationIndex)
		}
		// 拖拽更新 columnsOrder
		const _columnsOrder = [...columnsRef.current]
		_columnsOrder.splice(_sourceIndex, 1)
		_columnsOrder.splice(_destinationIndex, 0, columnsRef.current[_sourceIndex])
		columnsRef.current = _columnsOrder
		setColumnsOrder(() => _columnsOrder)
	}
	// 初始化表头
	const initColumns = () => {
		const _columns = [...columnsOrder]
		_columns.forEach((column, index) => {
			column.index = index
			column.title = (
				<div>
					<DraggableColumn key={index} id={column.key} index={index} fixed={column.fixed} onDrag={handleDrag}>
						{typeof column.title === "function" ? column.title() : ""}
						<ColumnHeader
							title={typeof column.title === "function" ? "" : (column.title as string)}
							sortable={column.sortable}
							onSort={!column.sortable ? undefined : () => handleSort(column.key)}
						/>
					</DraggableColumn>
				</div>
			)
		})
		setColumnsOrder(_columns)
	}
	const changeColumns = (col: any[]) => {
		columnsRef.current = col
		setColumnsOrder(() => col)
		propsChangeColumns?.(col)
	}
	const tableChange = (pagination: any, filters: any, sorter: any, extra: any) => {
		if (onChange) {
			onChange(pagination, filters, sorter, extra)
		}
		if (onPageChange) {
			onPageChange(pagination.current, pagination.pageSize)
		}
	}

	useEffect(() => {
		initColumns()
	}, [])

	return (
		<div id={tableId}>
			<div style={{ display: "flex", justifyContent: "space-between", padding: "10px 20px" }} className="statistic">
				<Statistics data={data} statisticText={statisticText} statisticDom={statisticDom} />
				<Active columns={columnsOrder} changeColumns={changeColumns} onExport={onExport} showRowSet={showRowSet} />
			</div>

			<STable
				sticky={sticky}
				summary={summary}
				loading={loading}
				tableLayout="fixed"
				columns={columnsOrder}
				dataSource={data}
				pagination={
					pagination
						? {
								pageSizeOptions,
								...pagination,
								showQuickJumper: true,
								showSizeChanger: true,
								showTotal: (total: number) => formatMessage({ id: "common.utils.total_n_records" }, { n: total })
						  }
						: false
				}
				onChange={tableChange}
				scroll={scroll}
				ref={tableRef}
				{...otherProps}
				rowKey={rowKey}
				rowSelection={rowSelection}
				footer={footer}
			/>
		</div>
	)
}

export default DropTable
